<template>
	<view class="tab-pane" :class="{ 'tab-pane--active': isActive }" :style="paneStyle" v-if="isActive || keepAlive">
		<slot />
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, onUnmounted, inject, watch, Ref } from 'vue';

	// 定义TabPane属性
	const props = defineProps<{
		// 唯一标识
		key ?: string | number;
		// 标签标题
		title : string;
		// 是否禁用
		disabled ?: boolean;
		// 是否保持状态
		keepAlive ?: boolean;
		// 自定义样式
		paneStyle ?: string;
	}>();

	// 获取从Tabs组件提供的属性和方法
	const tabs = inject<{
		activeKey : Ref<string | number>;
		registerPane : (pane : any) => void;
		unregisterPane : (key : string | number) => void;
	}>('tabs');

	if (!tabs) {
		throw new Error('TabPane must be used within Tabs component');
	}

	// 注册当前面板
	onMounted(() => {
		tabs.registerPane({
			key: props.key,
			title: props.title,
			disabled: props.disabled
		});
	});

	// 注销当前面板
	onUnmounted(() => {
		if (props.key !== undefined) {
			tabs.unregisterPane(props.key);
		}
	});

	// 监听属性变化，更新注册信息
	watch(
		() => [props.title, props.disabled],
		() => {
			// 先注销再重新注册以更新信息
			if (props.key !== undefined) {
				tabs.unregisterPane(props.key);
			}
			tabs.registerPane({
				key: props.key,
				title: props.title,
				disabled: props.disabled
			});
		}
	);

	// 判断当前面板是否激活
	const isActive = ref(false);

	// 监听激活状态变化
	watch(
		() => tabs.activeKey.value,
		(newVal) => {
			isActive.value = newVal === props.key;
		},
		{ immediate: true }
	);
</script>

<style scoped>
	.tab-pane {
		width: 100%;
		min-height: 100%;
		box-sizing: border-box;
		display: none;
	}

	.tab-pane--active {
		display: block;
		animation: fadeIn 0.3s ease;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>